﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using XinYiOffice.Common;
using XinYiOffice.BLL;
using XinYiOffice.Basic;
using System.Data;
using System.Text;
using XinYiOffice.Config;

namespace XinYiOffice.Web.Call
{
    public partial class Ajax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string action = xytools.url_get("action");
            switch (action.ToLower())
            {
                case "login":
                    Login();
                    break;

                case "getcolumns":
                    GetColumns();
                    break;

                case "getcity":
                    GetCity();
                    break;

                case "getmarketingplan":
                    GetMarketingPlan();
                    break;

                case "getofficeworkeraccount":
                    GetOfficeWorkerAccount();
                    break;

                case "getclientinfo":
                    GetClientInfo();
                    break;

                case "getclientliaisons":
                    GetClientLiaisons();
                    break;

                case "getproject_class":
                    GetProjectClass();
                    break;

                case "getproject":
                    GetProject();
                    break;

                case "getsopp":
                    GetSalesOpportunities();
                    break;

                case "getofficeworker":
                    //获取职员列表
                    GetOfficeWorkerList();
                    break;

                case "getotherofficeworker":
                    //获取其他职员列表
                    GetOtherOfficeWorker();
                    break;

                case "getotherofficeworkeraccount":
                    //GetOtherOfficeWorkerAccount(); // 获取其他机构的帐号列表
                    break;

                case "getinstitution":
                    GetInstitution();
                    break;

                case "getdepartmentbyins":
                    GetDepartment();
                    break;

                case "getofficeworkerbyins":
                    GetOfficeWorkerByIns();
                    break;

                case "getofficeworkerbydep":
                    GetOfficeWorkerByDep();
                    break;

                case "getdictionarytable":
                    GetDictionaryTable();
                    break;

                case "setqiandao":
                    SetQiandao();
                    break;

                case "setqiantui":
                    SetQiantui();
                    break;
            }
        }

        public void SetQiantui()
        {
            int aid = AppDataCacheServer.CurrentAccountId();
            try
            {
                Model.Programme p = new Model.Programme();
                List<Model.Programme> pList = new BLL.Programme().GetModelList(string.Format(" CreateAccountId={0} and (DATEPART(year,StartTime)={1} and DATEPART(month,StartTime)={2} and DATEPART(day,StartTime)={3}) ", aid, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day));
                p.CreateAccountId = aid;

                p.InstitutionId = 0;
                p.IsRemind = 0;
                p.IsRepeat = 0;
                p.Locale = "签到地";
                p.Note = "已签-签到";
                p.ProjectInfoId = 0;
                p.RefreshAccountId = aid;
                p.RefreshTime = DateTime.Now;
                p.RemindDay = 0;
                p.RepeatInterval = 0;
                p.ScheduleType = -99;
                p.StartTime = DateTime.Now;
                p.TenantId = AppDataCacheServer.CurrentTenantId();
                p.Title = "已签退-已签到";
                p.UpToDate = DateTime.Now;

                if (pList != null && pList.Count > 0)
                {
                    p = pList[0];
                    p.EndTime = DateTime.Now;

                    new BLL.Programme().Update(p);
                }
                else
                {
                    p.EndTime = DateTime.Now.AddHours(8);//默认加8小时
                    //new BLL.Programme().Add(p);
                }



                xytools.write("1");
            }
            catch (Exception ex)
            {
                EasyLog.WriteLog(ex);
                xytools.write("-99");
            }
        }

        public void SetQiandao()
        {
            int aid = AppDataCacheServer.CurrentAccountId();
            try
            {
                Model.Programme p = new Model.Programme();
                List<Model.Programme> pList = new BLL.Programme().GetModelList(string.Format(" CreateAccountId={0} and (DATEPART(year,StartTime)={1} and DATEPART(month,StartTime)={2} and DATEPART(day,StartTime)={3}) ",aid,DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day));
                p.CreateAccountId = aid;
                p.CreateTime = DateTime.Now;
               
                p.InstitutionId = 0;
                p.IsRemind = 0;
                p.IsRepeat = 0;
                p.Locale = "签到地";
                p.Note = "签到";
                p.ProjectInfoId = 0;
                p.RefreshAccountId = aid;
                p.RefreshTime = DateTime.Now;
                p.RemindDay = 0;
                p.RepeatInterval = 0;
                p.ScheduleType = -99;
                p.StartTime = DateTime.Now;
                p.TenantId = AppDataCacheServer.CurrentTenantId();
                p.Title = "已签到";
                p.UpToDate = DateTime.Now;

                if (pList != null && pList.Count > 0)
                {
                    p = pList[0];

                    new BLL.Programme().Update(p);
                }
                else
                {
                    p.EndTime = DateTime.Now.AddDays(-1);//默认减一天
                    new BLL.Programme().Add(p);
                }
                
                
                
                xytools.write("1");
            }
            catch(Exception ex)
            {
                EasyLog.WriteLog(ex);
                xytools.write("-99");
            }

        }



        /// <summary>
        /// 获取字典表 字段
        /// </summary>
        protected void GetDictionaryTable()
        {
            string _w = string.Empty;
            string _tablename = xytools.url_get("table");
            string _field = xytools.url_get("field");

            if (xytools.DataIsNoNull(_tablename, _field))
            {
                string mysql = string.Format("select Value as value,DisplayName as label from vDictionaryTable where TableName='{0}' and FieldName='{1}' and TenantId={2} ", _tablename, _field,AppDataCacheServer.CurrentTenantId());
                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            xytools.write(_w);
        }


        /// <summary>
        /// 读取职员 按照部门id
        /// </summary>
        protected void GetOfficeWorkerByDep()
        {
            string _w = string.Empty;
            string depid = xytools.url_get("depid");
            if (SafeConvert.ToInt(depid) != 0)
            {
                string mysql = string.Format("select Id as value,FullName as label from OfficeWorker where DepartmentId=" + depid +" and TenantId="+AppDataCacheServer.CurrentTenantId());
                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            xytools.write(_w);
        }

        /// <summary>
        /// 读取职员 按照机构id
        /// </summary>
        protected void GetOfficeWorkerByIns()
        {
            string _w = string.Empty;
            string insid = xytools.url_get("insid");
            if (SafeConvert.ToInt(insid) != 0)
            {
                string mysql = string.Format("select Id as value,FullName as label from OfficeWorker where InstitutionId=" + insid +" and TenantId="+AppDataCacheServer.CurrentTenantId());
                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            xytools.write(_w);
        }


        /// <summary>
        /// 读取部门 按照机构id
        /// </summary>
        protected void GetDepartment()
        {
            string _w = string.Empty;
            string insid = xytools.url_get("insid");
            if (SafeConvert.ToInt(insid) != 0)
            {
                string mysql = string.Format("select Id as value,DepartmentName as label from Department where InstitutionId=" + insid+" and TenantId="+AppDataCacheServer.CurrentTenantId());
                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            xytools.write(_w);
        }

        /// <summary>
        /// 读取机构
        /// </summary>
        protected void GetInstitution()
        {
            string _w = string.Empty;
            string mysql = string.Format("select Id as value,OrganizationName label from Institution where TenantId="+AppDataCacheServer.CurrentTenantId());
            DataSet ds = DbHelperSQL.Query(mysql);
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
            }
            xytools.write(_w);
        }


        /// <summary>
        /// 获取联系人信息
        /// </summary>
        protected void GetClientLiaisons()
        {
            string _w = string.Empty;
            try
            {
                string term = xytools.url_get("term");
                string mysql = string.Empty;

                if (!string.IsNullOrEmpty(term))
                {
                    if (term != ".")
                    {
                        mysql = string.Format("select (FullName) as label,Id as value from ClientLiaisons where (FullName) like '%{0}%' and TenantId={1} order by CreateTime desc", term,AppDataCacheServer.CurrentTenantId());
                    }
                    else
                    {
                        mysql = string.Format("select top 10 (FullName) as label,Id as value from ClientLiaisons where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                    }
                }
                else
                {
                    mysql = string.Format("select top 10 (FullName) as label,Id as value from ClientLiaisons where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                }

                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch
            {
            }

            Response.Write(xytools.Trim(_w));
        }

        protected void GetSalesOpportunities()
        {
            string _w = string.Empty;
            try
            {

                string term = xytools.url_get("term");
                string mysql = string.Empty;

                if (!string.IsNullOrEmpty(term))
                {
                    if (term != ".")
                    {
                        mysql = string.Format("select (OppName) as label,Id as value from SalesOpportunities where (OppName) like '%{0}%' and TenantId={1} order by CreateTime desc", term,AppDataCacheServer.CurrentTenantId());
                    }
                    else
                    {
                        mysql = string.Format("select top 10 (OppName) as label,Id as value from SalesOpportunities where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                    }
                }
                else
                {
                    mysql = string.Format("select top 10 (OppName) as label,Id as value from SalesOpportunities where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                }

                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch
            {
            }

            Response.Write(xytools.Trim(_w));
        }

        /// <summary>
        /// 获取项目,根据年，月
        /// </summary>
        protected void GetProject()
        {
            string _write = string.Empty;
            string _year = xytools.url_get("year");
            string _month = xytools.url_get("month");

            try
            {
                string mysql = string.Empty;
                mysql = string.Format("select Title as label,Id as value from ProjectInfo where DATEPART(month,CreateTime)='{0}' and DATEPART(year,CreateTime)='{1}' and TenantId={2} order by CreateTime desc", _month, _year,AppDataCacheServer.CurrentTenantId());
                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _write = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch
            {
            }
            finally
            {
            }

            xytools.write(_write);
        }

        /// <summary>
        /// 获取模块一下
        /// </summary>
        protected void GetProjectClass()
        {
            string _write = string.Empty;
            string _pid = xytools.url_get("pid");

            try
            {
                string mysql = string.Empty;
                mysql = string.Format("select Title as label,Id as value from ProjectInfo where ParentProjectId={0} and TenantId={1} order by CreateTime desc", _pid,AppDataCacheServer.CurrentTenantId());
                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _write = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch
            {
            }
            finally
            {
            }

            xytools.write(_write);
        }

        protected void GetClientInfo()
        {
            string _w = string.Empty;
            try
            {

                string term = xytools.url_get("term");
                string mysql = string.Empty;

                if (!string.IsNullOrEmpty(term))
                {
                    if (term != ".")
                    {
                        mysql = string.Format("select (Name) as label,Id as value from ClientInfo where (Name) like '%{0}%' and TenantId={1} order by CreateTime desc", term,AppDataCacheServer.CurrentTenantId());
                    }
                    else
                    {
                        mysql = string.Format("select top 10 (Name) as label,Id as value from ClientInfo where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                    }
                }
                else
                {
                    mysql = string.Format("select top 10 (Name) as label,Id as value from ClientInfo where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                }

                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch
            {
            }

            Response.Write(xytools.Trim(_w));
        }

        /// <summary>
        /// 获取其他机构 职员列表
        /// </summary>
        protected void GetOtherOfficeWorker()
        {
            string _w = string.Empty;
            try
            {

                string term = xytools.url_get("term");
                string mysql = string.Empty;

                if (!string.IsNullOrEmpty(term))
                {
                    if (term != ".")
                    {
                        mysql = string.Format("select (FullName) as label,Id as value from OfficeWorker where (FullName) like '%{0}%' and TenantId={1} order by CreateTime desc", term,AppDataCacheServer.CurrentTenantId());
                    }
                    else
                    {
                        mysql = string.Format("select top 10 (FullName) as label,Id as value from OfficeWorker where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                    }
                }
                else
                {
                    mysql = string.Format("select top 10 (FullName) as label,Id as value from OfficeWorker where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                }

                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch (Exception ex)
            {
                EasyLog.WriteLog(ex);
            }

            Response.Write(xytools.Trim(_w));
        }

        /// <summary>
        /// 获取职员列表
        /// </summary>
        protected void GetOfficeWorkerList()
        {
            string _w = string.Empty;
            try
            {

                string term = xytools.url_get("term");
                string mysql = string.Empty;

                if (!string.IsNullOrEmpty(term))
                {
                    if (term != ".")
                    {
                        mysql = string.Format("select (FullName) as label,Id as value from OfficeWorker where (FullName) like '%{0}%' and TenantId={1} order by CreateTime desc", term,AppDataCacheServer.CurrentTenantId());
                    }
                    else
                    {
                        mysql = string.Format("select top 10 (FullName) as label,Id as value from OfficeWorker where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                    }
                }
                else
                {
                    mysql = string.Format("select top 10 (FullName) as label,Id as value from OfficeWorker where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                }

                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch (Exception ex)
            {
                EasyLog.WriteLog(ex);
            }

            Response.Write(xytools.Trim(_w));
        }

        /// <summary>
        /// 获取职员名及帐号
        /// </summary>
        protected void GetOfficeWorkerAccount()
        {
            string _w = string.Empty;
            try
            {

                string term = xytools.url_get("term");
                string mysql = string.Empty;

                if (!string.IsNullOrEmpty(term))
                {
                    if (term != ".")
                    {
                        mysql = string.Format("select (FullName) as label,Id as value from Accounts where (FullName) like '%{0}%' and TenantId={1} order by CreateTime desc", term,AppDataCacheServer.CurrentTenantId());
                    }
                    else
                    {
                        mysql = string.Format("select top 10 (FullName) as label,Id as value from Accounts where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                    }
                }
                else
                {
                    mysql = string.Format("select top 10 (FullName) as label,Id as value from Accounts where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                }

                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _w = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch (Exception ex)
            {
                EasyLog.WriteLog(ex);
            }

            Response.Write(xytools.Trim(_w));
        }

        /// <summary>
        /// 获取最近营销计划
        /// </summary>
        protected void GetMarketingPlan()
        {
            string _write = string.Empty;

            try
            {
                string mysql = string.Empty;
                mysql = string.Format("select top 20 ProgramName as label,Id as value from MarketingPlan where TenantId={0} order by CreateTime desc",AppDataCacheServer.CurrentTenantId());
                DataSet ds = DbHelperSQL.Query(mysql);
                if (ds != null && ds.Tables.Count > 0)
                {

                    _write = JsonHelper.DataTableToJsonClear(ds.Tables[0]);
                }
            }
            catch
            {
            }
            finally
            {
            }

            //Response.HeaderEncoding = Encoding.UTF8;
            //Response.ContentType = "application/json;";
            Response.Write(xytools.Trim(_write));
            //xytools.write(_write);

        }

        /// <summary>
        /// 获取城市列表
        /// </summary>
        protected void GetCity()
        {
            int pid = SafeConvert.ToInt(xytools.url_get("pid"), 0);
            string _write = string.Empty;
            if (pid != 0)
            {
                _write = JsonHelper.DataTable2Json(AppDataCacheServer.GetCityByPid(pid));
            }

            xytools.write(_write);
        }

        protected void GetColumns()
        {
            string _table = xytools.url_get("tablename");
            string _write = string.Empty;
            try
            {
                _write = JsonHelper.DataTable2Json(AppDataCacheServer.GetAllColumsByTableName(_table));
            }
            catch (Exception ex)
            {
                EasyLog.WriteLog(ex);
            }

            xytools.write(_write);
        }

        protected void Login()
        {
            string username = xytools.url_get("username");
            string pas = xytools.url_get("pas");
            string TenantId = xytools.url_get("TenantId");
            string TenantGuid = xytools.url_get("TenantGuid");

            int cookieday = 7;
            if (!string.IsNullOrEmpty(TenantGuid))
            {
                //从云登录，过来的请求为guid形式
                TenantId = LocalTenantsServer.GetLocalTenantIdByGuid(TenantGuid).ToString();
                TenantId = Common.DESEncrypt.Encrypt(TenantId);//加密处理,因为cookie里需要保存
            }
           

            bool state = AccountsServer.LoginValidation(username, pas, TenantId, cookieday);
            if (AccountsServer.State == 1)
            {
                SystemJournalServer.SetSysLog(string.Format("用户{0}登录成功!", username), AccountsServer.GetCliCookie(),AppDataCacheServer.CurrentTenantId());
            }
            else
            {
                SystemJournalServer.SetSysLog(string.Format("用户{0}登录失败!", username), -99, AppDataCacheServer.CurrentTenantId());
            }
            
            string msg=AccountsServer.State.ToString();

            //云登录成功返回创建cookie页
            if (msg =="1"&& !string.IsNullOrEmpty(TenantGuid))
            {
                string ym = DateTime.Now.ToString("yyyy-MM-DD hh:mm:ss");
                ym = Common.DESEncrypt.Encrypt(ym);

                string user = Common.DESEncrypt.Encrypt(username);
                string pass = Common.DESEncrypt.Encrypt(pas);

                string url = string.Format(xytools.ApplicationPath() + "/Call/CreateCookie.aspx?t={0}&u={1}&pass={2}&ym={3}&sj={4}", TenantId, user, pass,ym,new Random().Next(10000));
                msg = string.Format("1#{0}", url);
            }
            xytools.write(msg);
        }
    }
}